package com.sxx.beautifulcity.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.google.gson.Gson;
import com.sxx.beautifulcity.R;
import com.sxx.beautifulcity.adapter.BackGroundViewPagerAdapter;
import com.sxx.beautifulcity.application.ProjectApplication;
import com.sxx.beautifulcity.database.KeepHealthHelper;
import com.sxx.beautifulcity.entity.KeepHealthData;
import com.sxx.beautifulcity.entity.KeepHealthDataResult;
import com.sxx.beautifulcity.entity.KeepHealthWeatherData;
import com.sxx.beautifulcity.entity.greendao.KeepHealthDaoEntity;
import com.sxx.beautifulcity.utils.HanZiPinYinTranslate;
import com.sxx.beautifulcity.utils.VolleySingleton;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Handler;

/**
 * Created by dllo on 15/10/26.
 */
public class KeepHealthFragment extends Fragment implements View.OnClickListener {

    private TextView cityNameTv, weatherTv, tempTv, WDTv, WSTv, dataTv, start, I_tempTv, h_tempTv, linear_layout;
    private EditText cityNameEt;
    private int[] images = {R.mipmap.cloudy, R.mipmap.sunnies, R.mipmap.sunny, R.mipmap.smallraining
            , R.mipmap.bigraining, R.mipmap.snow};
    private ViewPager background_viewpager;
    private BackGroundViewPagerAdapter adapter;
    private android.os.Handler handler;
    private int index = 0;
    private KeepHealthHelper helper;

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            index = background_viewpager.getCurrentItem();
            background_viewpager.setCurrentItem(++index);
            handler.postDelayed(runnable,5000);
        }
    };

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        handler = new android.os.Handler();
    }

    /***
     * 加载布局
     *
     * @param inflater
     * @param container
     * @param savedInstanceState
     * @return
     */
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_keephealth_activity, null);

        return view;
    }

    /***
     * 初始化控件
     *
     * @param view
     * @param savedInstanceState
     */
    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        cityNameTv = (TextView) view.findViewById(R.id.cityNameTv);
        weatherTv = (TextView) view.findViewById(R.id.weatherTv);
        tempTv = (TextView) view.findViewById(R.id.tempTv);
        WDTv = (TextView) view.findViewById(R.id.WDTv);
        WSTv = (TextView) view.findViewById(R.id.WSTv);
        dataTv = (TextView) view.findViewById(R.id.dataTv);
        start = (TextView) view.findViewById(R.id.start);
        start.setOnClickListener(this);
        h_tempTv = (TextView) view.findViewById(R.id.h_tempTv);
        I_tempTv = (TextView) view.findViewById(R.id.I_tempTv);
        cityNameEt = (EditText) view.findViewById(R.id.cityNameEt);
        background_viewpager = (ViewPager) view.findViewById(R.id.background_viewpager);

    }

    /***
     * 写逻辑
     *
     * @param savedInstanceState
     */
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        adapter = new BackGroundViewPagerAdapter();
        background_viewpager.setAdapter(adapter);

        adapter.addData(images);
        handler.postDelayed(runnable,5000);

    }

    private void requestData() {
        String cityName = cityNameEt.getText().toString();
        char city = cityName.charAt(0);
        String pinyin = "";

        if (city >= 0x4e00 && city <= 0x9fa5) {
            pinyin = HanZiPinYinTranslate.getFirstSpell(cityName);
        } else {
            pinyin = cityName;
        }
        String httpUrl = "http://apis.baidu.com/apistore/weatherservice/weather";
        String httpArg = "citypinyin=" + pinyin;
        String path = httpUrl + "?" + httpArg;

        final JsonObjectRequest request = new JsonObjectRequest(path, null,
                new Response.Listener<JSONObject>() {

                    Gson gson = new Gson();
                    List<KeepHealthDaoEntity> datas = new ArrayList<>();

                    @Override
                    public void onResponse(JSONObject response) {

                        if (response != null && response.has("retData")) {
                            JSONObject retData = response.optJSONObject("retData");
                            String str = retData.toString();
                            KeepHealthDaoEntity data = gson.fromJson(str, KeepHealthDaoEntity.class);
                            cityNameTv.setText(data.getCity());
                            weatherTv.setText(data.getWeather());
                            tempTv.setText(data.getTemp());
                            WDTv.setText(data.getWD());
                            WSTv.setText(data.getWS());
                            dataTv.setText(data.getDate());
                            h_tempTv.setText(data.getH_tmp());
                            I_tempTv.setText(data.getL_tmp());
                            datas.add(data);
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        error.printStackTrace();
                    }
                }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put("apikey", "7df89e2ed7c7b92e1a2fe5ec8036d0cd");
                return map;
            }
        };
        VolleySingleton.getInstance().addRequest(request);
    }

    @Override
    public void onClick(View v) {
        InputMethodManager methodManager = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        methodManager.hideSoftInputFromWindow(v.getWindowToken(), 0);
        helper = new KeepHealthHelper();
        List<KeepHealthDaoEntity> entityList = helper.queryKeepHealthListAll();
        if (entityList.size() == 0) {
            requestData();
        }else{

        }
    }
}
